import logging
import datetime

from base.connection import get_db_session
from common.definition import OrderType

logger = logging.getLogger("wechat.helper.coupon")


def get_coupon(open_id, lucky_number):
    """
    新用户关注公众号发放券

    :param open_id:
    :param lucky_number: user number for lucky draw
    :return:
    """

    try:
        if lucky_number.endswith("9"):
            # 发放39元莱呗红酒券
            result1 = CouponHandler.create_coupon(open_id, 4)
            if result1:
                logger.info(f"get_coupon: success: open_id={open_id} coupon_id=4")
            else:
                logger.error(f"get_coupon: fail: open_id={open_id} coupon_id=4")

        # 发放满199元减100元抵扣券
        result2 = CouponHandler.create_coupon(open_id, 7)
        if result2:
            logger.info(f"get_coupon: success: open_id={open_id} coupon_id=7")
        else:
            logger.error(f"get_coupon: fail: open_id={open_id} coupon_id=7")
    except Exception as e:
        logger.error(f"get_coupon: fail: open_id={open_id} error={e}")
        return

    return


def get_available_coupons(store_id, order_type, open_id, total_price, goods_list, page_size, page_start, cu_id=None):
    """获取可用优惠券列表"""

    class CouponUser(object):
        pass

    class Coupon(object):
        pass

    session = get_db_session([
        {"db_table": "ebt_coupon", "model": Coupon},
        {"db_table": "ebt_coupon_user", "model": CouponUser}
    ])

    id_list = [g["id"] for g in goods_list]
    coupon_list = list()
    filters = dict(
        user_id=open_id,
        status=0,
        is_active=1
    )
    if cu_id:
        filters["id"] = cu_id
    cus = session.query(CouponUser).order_by(
        CouponUser.expiry_date.asc()).filter_by(**filters)[page_start: page_start + page_size]
    for cu in cus:
        cp_id = cu.coupon_id
        cp = session.query(Coupon).filter_by(id=cp_id).first()
        if not cp:
            logger.error(f"coupon表无记录: cp_id={cp_id}")
            continue

        create_time = cu.create_time
        effect_date = cu.effect_date
        expiry_date = cu.expiry_date
        is_active = cu.is_active
        buy_way = cp.buy_way  # 购买方式：0=通用 1=单独购买 2=参与拼柜
        full_money = cp.full_money
        goods_id = cp.goods_id
        use_range = cp.use_range  # 使用范围：0=通用 1=线上商城 2=线下门店
        if not buy_way:
            if goods_id:
                if full_money:
                    if goods_id in id_list and total_price >= full_money:
                        is_able_use = 1
                    elif goods_id in id_list and order_type == OrderType.PINGUI and full_money <= 400:
                        is_able_use = 1
                    else:
                        is_able_use = 0
                else:
                    if goods_id in id_list:
                        is_able_use = 1
                    else:
                        is_able_use = 0
            else:
                if full_money:
                    if total_price >= full_money:
                        is_able_use = 1
                    elif order_type == OrderType.PINGUI and full_money <= 400:
                        is_able_use = 1
                    else:
                        is_able_use = 0
                else:
                    is_able_use = 1

            if not use_range:
                pass
            elif use_range == 1:
                if store_id:
                    is_able_use = 0
                else:
                    pass
            elif use_range == 2:
                if store_id:
                    pass
                else:
                    is_able_use = 0
            else:
                pass
        elif buy_way == 1:
            if order_type == OrderType.PINGUI:
                is_able_use = 0
            else:
                if goods_id:
                    if full_money:
                        if goods_id in id_list and total_price >= full_money:
                            is_able_use = 1
                        else:
                            is_able_use = 0
                    else:
                        if goods_id in id_list:
                            is_able_use = 1
                        else:
                            is_able_use = 0
                else:
                    if full_money:
                        if total_price >= full_money:
                            is_able_use = 1
                        else:
                            is_able_use = 0
                    else:
                        is_able_use = 1

            if not use_range:
                pass
            elif use_range == 1:
                if store_id:
                    is_able_use = 0
                else:
                    pass
            elif use_range == 2:
                if store_id:
                    pass
                else:
                    is_able_use = 0
            else:
                pass
        elif buy_way == 2:
            if order_type == OrderType.PINGUI:
                if goods_id:
                    if full_money:
                        if goods_id in id_list and full_money <= 400:
                            is_able_use = 1
                        else:
                            is_able_use = 0
                    else:
                        if goods_id in id_list:
                            is_able_use = 1
                        else:
                            is_able_use = 0
                else:
                    if full_money:
                        if full_money <= 400:
                            is_able_use = 1
                        else:
                            is_able_use = 0
                    else:
                        is_able_use = 1
            else:
                is_able_use = 0

            if not use_range:
                pass
            elif use_range == 1:
                if store_id:
                    is_able_use = 0
                else:
                    pass
            elif use_range == 2:
                if store_id:
                    pass
                else:
                    is_able_use = 0
            else:
                pass
        else:
            is_able_use = 0

        coupon = dict(
            id=cu.id,
            coupon_money=round(float(cu.coupon_money), 2) if cu.coupon_money else 0,
            full_money=round(float(cp.full_money), 2) if cp.full_money else 0,
            order_id=cu.order_id,
            create_time=create_time.strftime("%Y-%m-%d %H:%M:%S"),
            status=cu.status,
            title=cp.title,
            type=cp_id,
            is_active=is_active,
            is_able_use=is_able_use,
            time_range=effect_date.strftime("%Y.%m.%d") + "-" + expiry_date.strftime("%Y.%m.%d")
        )
        coupon_list.append(coupon)

    coupon_list = sorted(coupon_list, key=lambda x: x['is_able_use'], reverse=True)
    session.close()
    return coupon_list


class CouponHandler(object):
    """优惠券处理类"""

    @staticmethod
    def create_coupon(open_id, cp_id, order_id=None, coupon_amount=None, goods_id=None,
                      status=0, is_active=1, store_id=None, count=1):
        """
        为用户创建优惠券
        :param open_id:
        :param cp_id:
        :param order_id: 没有默认为00000000000000000
        :param coupon_amount: 券额
        :param goods_id: 指定商品
        :param status: 状态 1=已使用 0=已领取未使用 -1=已过期 2=无效 3=未领取
        :param is_active: 是否生效 0=未生效, 1=生效
        :param store_id:
        :param count: 数量
        :return:
        """

        class CouponUser(object):
            pass

        class Coupon(object):
            pass

        session = get_db_session([
            {"db_table": "ebt_coupon", "model": Coupon},
            {"db_table": "ebt_coupon_user", "model": CouponUser}
        ])

        now = datetime.datetime.now()
        cp = session.query(Coupon).filter_by(id=cp_id).first()
        effective_days = cp.effective_days
        expiry_date = (now + datetime.timedelta(days=effective_days)).replace(hour=23, minute=59, second=58)

        full_money = cp.full_money
        money = cp.money
        if coupon_amount:
            money = coupon_amount

        cu_goods_id = cp.goods_id
        if goods_id:
            cu_goods_id = goods_id

        if not order_id:
            order_id = "00000000000000000"

        source_type = 1 if order_id == "00000000000000000" else 4  # 券来源: 1渠道领取 2金钱购买 3积分购买 4下单赠送
        effect_date = now if is_active else None
        expiry_date = expiry_date if is_active else None
        data_list = []
        for i in range(count):
            cu = CouponUser()
            cu.user_id = open_id
            cu.coupon_id = cp_id
            cu.order_id = order_id
            cu.store_id = store_id
            cu.source_type = source_type
            cu.coupon_money = money
            cu.full_money = full_money
            cu.goods_id = cu_goods_id
            cu.create_time = now
            cu.effect_date = effect_date
            cu.expiry_date = expiry_date
            cu.status = status
            cu.is_active = is_active
            data_list.append(cu)

        try:
            session.add_all(data_list)
            logger.info(f"create_coupon success: open_id={open_id} order_id={order_id} coupon_id={cp_id}")
        except Exception as e:
            logger.error(e)
            session.rollback()
            session.close()
            logger.error(f"create_coupon fail: open_id={open_id} order_id={order_id} coupon_id={cp_id}")
            return False

        session.commit()
        session.close()
        return True
